const mongoose = require("mongoose");
const slugify = require("../utils/slugify");

const postSchema = new mongoose.Schema(
    {
        title: { type: String, required: true, index: true },
        slug: { type: String, required: true, unique: true, index: true },
        content: { type: String, required: true }, // 可存 Markdown
        coverImageUrl: { type: String, default: "" },
        tags: [{ type: String, index: true }],
        published: { type: Boolean, default: false, index: true },
        publishedAt: { type: Date },
        author: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, index: true },
    },
    { timestamps: true }
);

// 创建时自动生成 slug；若冲突则追加短时间戳保证唯一
postSchema.pre("validate", async function (next) {
    if (this.isModified("title") || !this.slug) {
        let base = slugify(this.title);
        if (!base) base = "post";
        let cand = base;
        let i = 0;

        // 若存在同名 slug，追加递增后缀
        while (await mongoose.models.Post.exists({ slug: cand, _id: { $ne: this._id } })) {
            i += 1;
            cand = `${base}-${i}`;
        }
        this.slug = cand;
    }
    next();
});

postSchema.set("toJSON", {
    transform: (doc, ret) => {
        delete ret.__v;
        return ret;
    },
});

module.exports = mongoose.model("Post", postSchema);
